package czy.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 * 认证控制器,登录登出,获取当前用户信息
 */
@RestController
@RequestMapping("auth")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    /**
     * 自定义登陆接口,框架本身自带了登陆接口
     * @param username:用户名
     * @param password:用户密码
     * @param request:请求对象,用于登陆
     * @return:登陆是否成功
     * @throws ServletException:如果当前已有登陆用户,或者不支持用户名/密码登陆,或者认证失败,抛出异常
     */
    @GetMapping("login")
    public boolean login(
            @RequestParam String username,
            @RequestParam String password,
            HttpServletRequest request){
        logger.info("用户登录:username="+username+",password="+password);
        try{
            request.login(username,password);
            return true;
        }catch (ServletException ex){
            logger.error("登陆错误",ex);
            return false;
        }
    }

    /**
     * 登出接口
     * @return:是否成功
     */
    @GetMapping("logout")
    public boolean logout(HttpServletRequest request){
        try{
            request.logout();
            return true;
        }catch (ServletException ex){
            logger.error("登出错误",ex);
            return false;
        }
    }



}
